<?php
/**
 * 服务标准化PC后台控制器
 */
namespace Beerus\Modules\DesignerService\Controllers;

use App\Http\Controllers\Controller;
use Beerus\Modules\DesignerService\Actions\Remark;
use Beerus\Modules\DesignerService\Actions\ServiceFail;
use Beerus\Modules\DesignerService\Actions\ServicePass;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\DesignerService\ServiceAuditLog;
use Doraemon\model\DesignerService\ServiceContentRecord;
use Doraemon\model\DesignerService\DesignerServiceSpot;
use Doraemon\service\DesignerService\DesignerService as sDesignerService;
use Doraemon\model\Member;
use Doraemon\service\DesignerService\ServiceSpotService;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;

class ServiceContentAuditController extends Controller
{
	const PAGE_SIZE = 20;

	// 服务内容管理
	public function index(Request $request, Content $content)
	{
		$params = $request->all();

		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [
			'data_type' => ServiceContentRecord::TYPE_PUBLISHED
		];
		if (!empty($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}
		if (!empty($params['nick'])) {
			$uid = Member::get('uid', ['nick' => $params['nick']]);
			if ($uid) {
				$condition['uid'] = $uid;
			}
		}
		if (!empty($params['audit_status'])) {
			$condition['audit_status'] = $params['audit_status'];
		}

		$total = ServiceContentRecord::count($condition);

		$condition['ORDER'] = [
			'id' => 'DESC'
		];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = ServiceContentRecord::select('*', $condition);
		$this->formatList($lists);

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);

		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->setActionClass(DropdownActions::class);
				$grid->paginate($gridModel->getPerPage());
				$grid->perPages([10, 20, 30, 50, 100, 500]);
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
                $grid->tools(function ($tools) {
                    $button = '<div class="btn-group download" style="margin-right: 10px"> <a class="btn btn-sm btn-twitter" title="高级筛选" target="_blank" href="https://metabase.haohaozhu.me/question/3012"><i class="fa fa-filter"></i><span class="hidden-xs"> 高级筛选</span></a> </div>';
                    $tools->append($button);
                });

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('uid', 'UID')->placeholder('请输入设计师UID');
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('nick', '昵称')->placeholder('请输入设计师昵称');
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('audit_status', '审核状态')->select(ServiceContentRecord::AUDIT_TEXT);
					});
					$filter->expand();
				});

				$grid->column('id', 'ID')->width(60);
				$grid->column('uid', 'UID')->width(80);
				$grid->column('nick', '昵称')->width(100);
				$grid->column('operator', '对接运营');
				$grid->column('spot_name', '亮点标签')->display(function () {
					return $this->spot_name;
				})->width(250);
				$grid->column('add_time', '发布时间')->display(function () {
					$link = Hhzurl::getDomain() . "/designer/service-info?source=3&id={$this->id}";
					return '<a class="fa " href="javascript:layer.open({
					    type: 2,
	                    title: \'预览\', 
	                    maxmin: true, 
	                    area: [\'600px\', \'800px\'],
	                    fixed: false,
	                    offset: \'100px\',
	                    content: \'' . $link . '\' });">' . htmlentities($this->add_time) . '</a>';
				});
				$grid->column('remain_times', '当月剩余修改次数');
				$grid->column('audit_status', '审核状态')->using([
					0 => '其他',
					1 => '待审核',
					2 => '审核通过',
					3 => '审核不通过',
				], '未知')->dot([
					0 => 'primary',
					1 => 'info',
					2 => 'success',
					3 => 'danger',
				], 'warning');
				$grid->column('remark', '备注');
                $grid->column('audit_remark', '审核理由');
				$grid->column('edit_time', '审核时间');
				$grid->column('admin_name', '最后审核人');
				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					//$actions->disableEdit();
					$actions->disableView();

					if ($actions->row->audit_status == ServiceContentRecord::AUDIT_WAIT) {
						$actions->add(new ServicePass);
						$actions->add(new ServiceFail);
					}
					$actions->add(new Remark);
				});
			}
		);

		$tab = new Tab();
		$tab->add('服务指南审核列表', $gridList->render());
		$content->row($tab);
		return $content
			->header('服务指南审核')
			->description(' ')
			->breadcrumb(['text' => '服务指南审核']);
	}

	public function formatList(&$list)
	{
		foreach ($list as &$item) {
			$item['nick'] = Member::get('nick', ['uid' => $item['uid']]);
			$item['operator'] = DesignerOperatorBind::getOperatorAdminNameByUid($item['uid']) ?? '未认领';
            $selectedSpotList = DesignerServiceSpot::getSpotListByStatus($item['uid'], DesignerServiceSpot::SELECTED);
            $item['spot_name'] = $selectedSpotList ? ServiceSpotService::getDisplaySpotName($selectedSpotList) : '未设置';
			$item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
			$item['edit_time'] = empty($item['edit_time']) ? '-' : date('Y-m-d H:i:s', $item['edit_time']);
			$item['remain_times'] = sDesignerService::canReleaseNum($item['uid']);
			$item['admin_name'] = empty($item['admin_name']) ? '-' : $item['admin_name'];
		}
		unset($item);
	}

	public function edit(Request $request, Content $content, $id = 0)
	{
		$data = ServiceContentRecord::get('*', [
			'id' => $id
		]);
		$form = new Form($data);
		$form->hidden('id', '服务指南id');
		$form->select('audit_status', '审核状态')->setWidth(4, 2)
			->options(ServiceContentRecord::AUDIT_TEXT)
			->required('不能为空');
		$form->textarea('remark', '备注')->setWidth(4, 2);
		$form->confirm('确认提交吗？');

		$form->disableReset();
		$form->action('/admin/DesignerService/service_audit/save');

		$tab = new Tab();
		$tab->add('编辑服务指南信息', $form->render());
		return $content->header('服务指南详情')
			->breadcrumb([
				'text' => '服务指南审核列表',
				'url' => route('service_audit.list')
			], ['text' => '服务指南详情'])->row($tab);
	}

	public function save(Request $request)
	{
		$params = $request->all();

		$res = ServiceContentRecord::update([
			'audit_status' => $params['audit_status'],
			'remark' => $params['remark'],
			'edit_time' => time(),
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username
		], [
			'id' => $params['id']
		]);

		if ($res) {
			ServiceAuditLog::insert([
				'service_content_id' => $params['id'],
				'op' => ServiceContentRecord::AUDIT_TEXT[$params['audit_status']],
				'admin_id' => Admin::user()->id,
				'admin_name' => Admin::user()->username
			]);
			$success = new MessageBag([
				'title' => '操作成功(＾－＾)V'
			]);

			return back()->with(compact('success'));
		}else{
			$error = new MessageBag([
				'title' => '操作失败,请稍后重试o(TωT)o'
			]);

			return back()->with(compact('error'));
		}
	}
}
